"""
循环经济回收网络优化模块
"""
import json
import os

class OptimizationEngine:
    def __init__(self):
        # 从JSON文件加载产品数据
        self.product_data = self._load_product_data()
        # 地区基础设施数据
        self.region_data = {
            'urban': {
                'population_density': 'high',
                'existing_facilities': 5,
                'transport_cost': 0.5  # 元/公里/千克
            },
            'suburban': {
                'population_density': 'medium',
                'existing_facilities': 2,
                'transport_cost': 0.8
            },
            'rural': {
                'population_density': 'low',
                'existing_facilities': 1,
                'transport_cost': 1.2
            }
        }
    
    def _load_product_data(self):
        """加载产品数据"""
        data_path = os.path.join(os.path.dirname(__file__), 'data', 'products.json')
        try:
            with open(data_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                return {p['type']: p for p in data['products']}
        except Exception as e:
            raise ValueError(f"无法加载产品数据: {str(e)}")
    
    def optimize_network(self, product_type, quantity, region_type):
        """
        优化回收网络布局
        参数:
            product_type: 产品类型
            quantity: 数量
            region_type: 地区类型(urban/suburban/rural)
        返回:
            字典包含优化建议
        """
        if region_type not in self.region_data:
            raise ValueError(f"不支持的地区类型: {region_type}. 请使用urban/suburban/rural")
        if product_type not in self.product_data:
            supported = ", ".join(self.product_data.keys())
            raise ValueError(f"不支持的产品类型: {product_type}. 支持: {supported}")
            
        region = self.region_data[region_type]
        product = self.product_data[product_type]
        
        # 计算总重量(kg)
        total_weight = product['weight_kg'] * quantity
        
        # 计算建议新增回收点数量（基于重量）
        weight_per_facility = {
            'urban': 500,    # 每个设施处理500kg
            'suburban': 300,
            'rural': 200
        }
        required_facilities = max(1, round(total_weight / weight_per_facility[region_type]))
        new_facilities = max(0, required_facilities - region['existing_facilities'])
        
        # 计算运输成本（按重量和距离）
        avg_distance = 15 if region['population_density'] == 'high' else 25
        transport_cost = avg_distance * region['transport_cost'] * total_weight
        
        # 生成详细优化建议
        recommendations = [
            f"产品类型: {product_type} (单重: {product['weight_kg']}kg)",
            f"在{region_type}地区建议{'新增' if new_facilities > 0 else '无需新增'}回收点",
            f"建议总数: {required_facilities}个 (现有: {region['existing_facilities']})",
            f"预估运输成本: {round(transport_cost, 2)}元 (距离: {avg_distance}公里)",
            "具体建议:",
            "- 优先在商业区设立" if region_type == 'urban' else 
              "- 考虑流动回收车" if region_type == 'suburban' else 
              "- 与社区中心合作",
            "- 需专业处理设备" if product['hazardous_material'] > 0.15 else 
              "- 可简化回收流程"
        ]
        
        return {
            '地区类型': region_type,
            '产品类型': product_type,
            '回收量(kg)': total_weight,
            '现有设施': region['existing_facilities'],
            '建议总数': required_facilities,
            '建议新增': new_facilities,
            '运输成本(元)': round(transport_cost, 2),
            '优化建议': recommendations
        }